package com.bulletelc.apollopre.module.main.center.orders;

import android.content.Context;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.OrderDetailBean;
import com.bulletelc.apollopre.manager.imageload.ImageLoaderManager;
import com.bulletelc.apollopre.module.main.center.orders.detail.OrderDetailActivity;

import java.math.BigDecimal;
import java.util.List;

/**
 * author: lhl
 * date  : 2018/01/26
 * desc  : 我的订单列表 的adapter
 */

public class OrderListAdapter extends BaseExpandableListAdapter implements View.OnClickListener {

    private Context context;
    private List<OrderDetailBean> orderDetailBeans;
    private LayoutInflater inflater;

    private static final int CHILD_TYPE_PRODUCT = 0;
    private static final int CHILD_TYPE_FOOTER = 1;

    private OnClickListener onClickListener;

    public OrderListAdapter(Context context, List<OrderDetailBean> orderDetailBeans) {
        this.context = context;
        this.orderDetailBeans = orderDetailBeans;
        this.inflater = LayoutInflater.from(context);
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    @Override
    public int getGroupCount() {
        if (orderDetailBeans != null) {
            return orderDetailBeans.size();
        }
        return 0;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (orderDetailBeans != null) {
            return orderDetailBeans.get(groupPosition).getSales_order_items().size() + 1;
        }
        return 0;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return orderDetailBeans.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return orderDetailBeans.get(groupPosition).getSales_order_items().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public int getChildTypeCount() {
        return 2;
    }

    @Override
    public int getChildType(int groupPosition, int childPosition) {
        if (childPosition == (getChildrenCount(groupPosition)) - 1) {
            return 1;
        }
        return 0;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        OrderDetailBean bean = orderDetailBeans.get(groupPosition);
        ViewHolderParent holderParent;
        if (convertView == null) {
            holderParent = new ViewHolderParent();
            convertView = inflater.inflate(R.layout.elv_order_list_parent_layout, parent, false);
            holderParent.tvSupplierLabel = convertView.findViewById(R.id.tvSupplierLabel);
            holderParent.tvStateLabel = convertView.findViewById(R.id.tvStateLabel);
            convertView.setTag(holderParent);
        } else {
            holderParent = (ViewHolderParent) convertView.getTag();
        }

        holderParent.tvSupplierLabel.setText(bean.getSupplier_label());
        holderParent.tvStateLabel.setText(bean.getState_label());

        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        ViewHolderChild holderChild = null;
        ViewHolderChildFooter childFooter = null;
        int type = getChildType(groupPosition, childPosition);

        if (convertView == null) {
            switch (type) {
                case CHILD_TYPE_PRODUCT:
                    holderChild = new ViewHolderChild();
                    convertView = inflater.inflate(R.layout.elv_order_list_child_layout, parent, false);
                    holderChild.rlChildOrder = convertView.findViewById(R.id.rlChildOrder);
                    holderChild.ivImg = convertView.findViewById(R.id.ivImg);
                    holderChild.tvName = convertView.findViewById(R.id.tvName);
                    holderChild.tvSku = convertView.findViewById(R.id.tvSku);
                    holderChild.tvPrice = convertView.findViewById(R.id.tvPrice);
                    holderChild.tvNum = convertView.findViewById(R.id.tvNum);

                    holderChild.rlChildOrder.setOnClickListener(this);

                    convertView.setTag(R.id.tag_order_list_child, holderChild);
                    break;
                case CHILD_TYPE_FOOTER:
                    childFooter = new ViewHolderChildFooter();
                    convertView = inflater.inflate(R.layout.elv_order_list_child_footer_layout, parent, false);
                    childFooter.tvTotalNum = convertView.findViewById(R.id.tvTotalNum);
                    childFooter.tvTotalMoney = convertView.findViewById(R.id.tvTotalMoney);
                    childFooter.rlGoto = convertView.findViewById(R.id.rlGoto);
                    childFooter.btnGoTo = convertView.findViewById(R.id.btnGoTo);
                    childFooter.btnCancelOrder = convertView.findViewById(R.id.btnCancelOrder);
                    childFooter.tvGroupStatus = convertView.findViewById(R.id.tvGroupStatus);
                    childFooter.clGroup = convertView.findViewById(R.id.clGroup);

                    childFooter.btnGoTo.setOnClickListener(this);
                    childFooter.btnCancelOrder.setOnClickListener(this);

                    convertView.setTag(R.id.tag_order_list_child_footer, childFooter);
                    break;
            }


        } else {
            switch (type) {
                case CHILD_TYPE_PRODUCT:
                    holderChild = (ViewHolderChild) convertView.getTag(R.id.tag_order_list_child);
                    break;

                case CHILD_TYPE_FOOTER:
                    childFooter = (ViewHolderChildFooter) convertView.getTag(R.id.tag_order_list_child_footer);
                    break;
            }


        }

        switch (type) {
            case CHILD_TYPE_PRODUCT:
                OrderDetailBean.SalesOrderItemsBean salesOrderItemsBean = orderDetailBeans.get(groupPosition).getSales_order_items().get(childPosition);
                holderChild.tvName.setText(salesOrderItemsBean.getProduct_name());
                holderChild.tvSku.setText(salesOrderItemsBean.getSku_label());
                holderChild.tvPrice.setText("¥" + salesOrderItemsBean.getSale_price());
                holderChild.tvNum.setText("x" + salesOrderItemsBean.getQuantity());
                ImageLoaderManager.getInstance().loadImage(ImageLoaderManager.getDefaultOptions(holderChild.ivImg, salesOrderItemsBean.getProduct_images().getOriginal()));

                holderChild.rlChildOrder.setTag(R.id.tag_order_list_rl_parent, groupPosition);

                break;

            case CHILD_TYPE_FOOTER:
                childFooter.tvTotalNum.setText("共" + getQuantity(groupPosition) + "件商品");
                childFooter.tvTotalMoney.setText("¥" + orderDetailBeans.get(groupPosition).getGrand_total());
                childFooter.btnGoTo.setTag(R.id.tag_order_list_btn_position, groupPosition);
                childFooter.btnCancelOrder.setTag(groupPosition);
                int state = orderDetailBeans.get(groupPosition).getState();
                int commentState = orderDetailBeans.get(groupPosition).getComment_state();
                int groupState = orderDetailBeans.get(groupPosition).getGroup_state();
                switch (state) {
                    case GlobalConfig.ORDER_STATE_UN_PAID:
                        childFooter.btnGoTo.setText("付款");
                        childFooter.btnCancelOrder.setText("取消订单");
                        childFooter.btnGoTo.setVisibility(View.VISIBLE);
                        childFooter.btnCancelOrder.setVisibility(View.VISIBLE);
                        break;

                    case GlobalConfig.ORDER_STATE_UN_SEND:
                        //childFooter.rlGoto.setVisibility(View.GONE);
                        childFooter.btnCancelOrder.setText("申请退货");
                        setGroupStateMsg(groupState, childFooter, groupPosition);
                        childFooter.btnCancelOrder.setVisibility(View.VISIBLE);
                        childFooter.btnGoTo.setVisibility(View.GONE);
                        break;

                    case GlobalConfig.ORDER_STATE_UN_SIGN:
                        childFooter.btnGoTo.setText("确认签收");
                        childFooter.btnCancelOrder.setText("申请退货");
                        setGroupStateMsg(groupState, childFooter, groupPosition);
                        childFooter.btnGoTo.setVisibility(View.VISIBLE);
                        childFooter.btnCancelOrder.setVisibility(View.VISIBLE);
                        break;

                    case GlobalConfig.ORDER_STATE_COMPLETE:
                        if (commentState == GlobalConfig.ORDER_STATE_UN_COMMENT) {
                            childFooter.btnGoTo.setText("评价");
                            childFooter.btnGoTo.setVisibility(View.VISIBLE);
                        } else {
                            childFooter.btnGoTo.setVisibility(View.GONE);
                            childFooter.btnCancelOrder.setVisibility(View.GONE);
                        }
                        //完成订单暂时不能退货，除非需求修改
                        //childFooter.btnCancelOrder.setText("申请退货");
                        //childFooter.btnCancelOrder.setVisibility(View.VISIBLE);
                        break;

                    case GlobalConfig.ORDER_STATE_AFTER_SALE://售后中
                        childFooter.btnGoTo.setVisibility(View.GONE);
                        childFooter.btnCancelOrder.setVisibility(View.GONE);
                        break;

                    case GlobalConfig.ORDER_STATE_CANCEL://订单取消
                        childFooter.btnGoTo.setVisibility(View.GONE);
                        childFooter.btnCancelOrder.setVisibility(View.GONE);
                        break;

                }


                break;
        }
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    /**
     * 获取商品共数量
     *
     * @param position
     * @return
     */
    private int getQuantity(int position) {
        int quantity = 0;
        List<OrderDetailBean.SalesOrderItemsBean> salesOrderItemsBeans = orderDetailBeans.get(position).getSales_order_items();
        for (int i = 0, size = salesOrderItemsBeans.size(); i < size; i++) {
            quantity += salesOrderItemsBeans.get(i).getQuantity();
        }
        return quantity;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rlChildOrder:
                int positionRl = (int) v.getTag(R.id.tag_order_list_rl_parent);
                goToActivity(positionRl);

                break;

            case R.id.btnGoTo:
                int position = (int) v.getTag(R.id.tag_order_list_btn_position);
                goToActivity(position);
                break;

            case R.id.btnCancelOrder: //取消订单/申请退货
                int position2 = (int) v.getTag();
                int state = orderDetailBeans.get(position2).getState();
                switch (state) {
                    case GlobalConfig.ORDER_STATE_UN_PAID:
                        if (onClickListener != null) {
                            onClickListener.onClick(position2);
                        }
                        break;

                    case GlobalConfig.ORDER_STATE_UN_SEND:
                    case GlobalConfig.ORDER_STATE_UN_SIGN:
                    case GlobalConfig.ORDER_STATE_COMPLETE:
                        //跳转到订单详情页
                        goToActivity(position2);
                        break;

                }

                break;
        }
    }

    /**
     * 进行精度除法
     *
     * @param salePrice
     * @param quantity
     * @return
     */
    private String divide(double salePrice, int quantity) {
        BigDecimal price = new BigDecimal(salePrice);
        BigDecimal bigDecimal = price.divide(new BigDecimal(quantity), 2, BigDecimal.ROUND_HALF_UP);
        return bigDecimal.toString();
    }

    /**
     * 跳转到订单详情页
     *
     * @param position
     */
    private void goToActivity(int position) {

        Intent intent = new Intent(context, OrderDetailActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_ORDER_ID, orderDetailBeans.get(position).getId());
        context.startActivity(intent);
    }


    private static class ViewHolderParent {
        private TextView tvSupplierLabel, tvStateLabel;
    }

    private static class ViewHolderChild {
        private RelativeLayout rlChildOrder;
        private ImageView ivImg;
        private TextView tvName;
        private TextView tvSku;
        private TextView tvPrice;
        private TextView tvNum;
    }

    private static class ViewHolderChildFooter {
        private TextView tvTotalNum, tvTotalMoney, tvGroupStatus;
        private RelativeLayout rlGoto;
        private Button btnGoTo;
        private Button btnCancelOrder;
        private ConstraintLayout clGroup;
    }

    public interface OnClickListener {
        /**
         * 当按钮点击(取消订单按钮)
         *
         * @param groupPosition
         */
        void onClick(int groupPosition);
    }

    /**
     * 设置砍价状态信息
     * @param groupState
     * @param childFooter
     * @param groupPosition
     */
    private void setGroupStateMsg(int groupState, ViewHolderChildFooter childFooter, int groupPosition) {
        if (groupState != 0) {
            childFooter.clGroup.setVisibility(View.VISIBLE);
            switch (groupState) {
                case 10:
                    childFooter.tvGroupStatus.setText("需要" + orderDetailBeans.get(groupPosition).getGroup_team_number() + "位好友,现有" + orderDetailBeans.get(groupPosition).getCurrently_group_member_number() + "位好友");
                    break;
                case 20:
                    childFooter.tvGroupStatus.setText(R.string.order_detail_cut_price_success);
                    break;
                case 30:
                    childFooter.tvGroupStatus.setText(R.string.order_detail_cut_price_fail);
                    break;
            }
        }
    }
}
